/* eslint-disable array-callback-return */
import React, { PureComponent } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, Input, Select, message, Tooltip } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import { urlParse } from '@/utils/utils';
import Area from '../../components/Area'; // 地区

const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
@connect(({ login, waresave }) => ({
  login,
  waresave,
}))
@Form.create()
class AccuWareEdit extends PureComponent {
  state = {
    YES_NO_FLAG: [],
    comList: [],
    supplyList: [],
    accoStatus: '',
    accuAccoId: '',
    statusFlag: false,
    proFundListFlag: false,
    sysCode: 1,
    supplyListFlag: true, // 公积金组合是否在下拉中
    respList: [],
  };

  componentDidMount() {
    const { login, dispatch, form, location } = this.props;
    const { userType } = login.baseUser;
    this.setState({ comDis: +userType !== 1 });
    const { accuAccoId, accoStatus } = this.state;
    const { systemList } = login;
    const { sysCode } = systemList.filter(item => item.isSelected)[0];
    this.setState({
      sysCode,
    });
    // 字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['YES_NO_FLAG'],
    }).then(res => {
      this.setState({ YES_NO_FLAG: res.YES_NO_FLAG });
      const accuAccoIds = urlParse(location.search).accuAccoId
        ? urlParse(location.search).accuAccoId
        : accuAccoId;
      const accoStatuss = urlParse(location.search).accoStatus
        ? urlParse(location.search).accoStatus
        : accoStatus;
      this.setState({
        statusFlag: +accoStatuss !== 1,
        accuAccoId: accuAccoIds,
        accoStatus: accoStatuss,
      });
      this.detail(accuAccoIds);
    });
    // 获取企业信息
    dispatch({
      type: 'waresave/fetchAccuCorpList',
      payload: {},
    }).then(res => {
      if (+userType === 1) {
        this.setState({ comList: res.data, unitId: res.data.unitId });
      } else {
        form.setFieldsValue({
          uniCreditCode: res.data[0].uniCreditCode,
          unitName: res.data[0].companyName,
        });
      }
    });
    this.getRespList();
  }

  // 查询负责人列表
  getRespList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'waresave/fetchUserId',
      payload: {},
    });
  };

  // 申报负责人备注内容
  renderRepListTip = () => (
    <Tooltip
      placement="right"
      title="只可以选择具有社保公积金系统权限的人员，只有设置的人员可查看该大库的增减员申报信息。"
    >
      <span>申报负责人</span>
      <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
    </Tooltip>
  );

  // 详情
  detail = accuAccoId => {
    const { form, waresave } = this.props;
    const obj = {};
    obj.accuAccoId = accuAccoId;
    const { dispatch } = this.props;
    dispatch({
      type: 'waresave/fetchAccuDetail',
      payload: obj,
    }).then(async res => {
      this.setState({
        respList: res.data.respList,
      });
      if (res.success) {
        const values = res.data;
        const getFieldsList = form.getFieldsValue();
        this.setState({
          unitId: res.data.unitId,
        });

        Object.keys(getFieldsList).forEach(async key => {
          if (values[key]) {
            if (key === 'isExceedCeiling') {
              form.setFieldsValue({ [key]: `${values[key]}` });
            } else if (key === 'areaId') {
              const tempAreaName = values.areaName || '石家庄市(河北省)';
              form.setFieldsValue({
                areaId: { key: values.areaId, label: values.areaName },
              });
              this.setState({
                selectedAreaId: values.areaId,
                areaName: tempAreaName,
              });
              await this.getproFundList(values.areaId);
            } else if (key === 'accuLsPkgIdsList') {
              const { supplyList } = this.state;
              const tempArr = [];
              values.accuPkgList.forEach(item => {
                if (supplyList.some(h => h.accuLsPkgId === item.accuLsPkgId)) {
                  tempArr.push(item.accuLsPkgId);
                } else {
                  this.setState({
                    supplyListFlag: false,
                    accuPkgList: values.accuPkgList,
                  });
                  tempArr.push(item.accuLsPkgName);
                }
              });
              form.setFieldsValue({
                accuLsPkgIdsList: tempArr,
              });
            } else if (key === 'respList') {
              const arr = [];
              values[key].map(item => {
                // 转换内容，能匹配到负责人push Id，不能的push Name
                if (waresave.respDataList.some(pdItem => pdItem.userId === item.respId)) {
                  arr.push(item.respId);
                } else {
                  arr.push(item.respName);
                }
                return true;
              });
              form.setFieldsValue({
                [key]: arr,
              });
            } else {
              form.setFieldsValue({ [key]: values[key] });
            }
          }
        });
      } else {
        message.warning(res.message);
      }
    });
  };

  tojson = arr => {
    if (!arr.length) return null;
    const arrays = [];
    for (let i = 0; i < arr.length; i += 1) {
      arrays.push({
        key: arr[i].accuLsPkgId,
        label: arr[i].accuLsPkgName,
      });
    }
    return arrays;
  };

  comInfoChange = value => {
    const { comList } = this.state;
    const { form } = this.props;
    comList.map(item => {
      if (item.corpId === value) {
        form.setFieldsValue({
          uniCreditCode: item.uniCreditCode,
        });
        this.setState({
          unitId: item.corpId,
        });
      }
      return true;
    });
  };

  // 表单检测 并 提交
  submitAll = () => {
    const { dispatch, form, waresave } = this.props;
    const { comList } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const {
          accuAccoId,
          supplyListFlag,
          accuPkgList,
          unitId,
          selectedAreaId,
          areaName,
          respList,
        } = this.state;
        const newV = values;
        if (values.areaId === areaName) {
          newV.areaId = selectedAreaId;
        } else {
          newV.areaId = values.areaId.key;
        }
        newV.unitId = unitId;
        newV.unitName = comList.length
          ? comList.filter(item => item.corpId === unitId)[0].companyName
          : newV.unitName;

        const newRespList = [];
        if (newV.respList.length) {
          // 申报负责人回转，将显示中文的转换回字典值
          newV.respList.map(items => {
            if (waresave.respDataList.some(pdItem => pdItem.userId === items)) {
              newRespList.push(items);
            } else {
              respList.map(value => {
                if (value.respName === items) {
                  newRespList.push(value.respId);
                }
              });
            }
          });
        }
        newV.respList = newRespList;

        const tempValues = JSON.parse(JSON.stringify(newV));
        if (!supplyListFlag) {
          if (tempValues.accuLsPkgIdsList.length) {
            tempValues.accuLsPkgIdsList.forEach((item, i, arr) => {
              const newArr = arr;
              accuPkgList.forEach(h => {
                if (h.accuLsPkgName === item) {
                  newArr[i] = h.accuLsPkgId;
                }
              });
            });
          }
        }
        dispatch({
          type: 'waresave/fetchUpdate',
          payload: { ...tempValues, accuAccoId },
        }).then(res => {
          if (res.success) {
            router.goBack();
          } else {
            message.error(res.message);
          }
        });
      }
    });
  };

  getData = (value, id) => {
    const tempAreaId = value.key;
    this.setState({ selectedAreaId: tempAreaId });
    this.getproFundList(tempAreaId);
    const { form } = this.props;
    form.setFieldsValue({ [id]: { key: tempAreaId } });
  };

  // 运行政策名称（公积金组）
  getproFundList = async areaId => {
    const { dispatch, form } = this.props;
    const { proFundListFlag } = this.state;
    // 获取企业信息
    await dispatch({
      type: 'waresave/fetchAccuLsPkg',
      payload: { areaId },
    }).then(res => {
      if (res.success) {
        this.setState({
          supplyList: res.data || [],
        });
      }
      if (proFundListFlag) {
        form.setFieldsValue({
          accuLsPkgIdsList: [],
        });
      }
      this.setState({
        proFundListFlag: true,
      });
    });
  };

  cancel = () => {
    router.goBack();
  };

  // 渲染函数
  render() {
    const { form, submitting, waresave } = this.props;
    const { getFieldDecorator } = form;
    const {
      YES_NO_FLAG,
      statusFlag,
      comList,
      sysCode,
      accoStatus,
      comDis,
      supplyList,
    } = this.state;
    const dictOL = dictList =>
      dictList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);
    const comOption = comList.map(value => (
      <Option key={value.corpId} value={value.corpId}>
        {value.companyName}
      </Option>
    ));
    const bDisable = +accoStatus === 2 || +accoStatus === 3;
    return (
      <Form layout="vertical">
        <PageHeaderWrapper>
          <Card title={<span>公积金账户信息</span>} bordered={false}>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="大库名称">
                  {getFieldDecorator('accoName', {
                    rules: [{ required: true, pattern:/^(?!\.)[^\\/:*?"<>|]{1,255}$/,message: '文件名不能包含下列任何字符  \\  /  :  *   ?  "  <  >  |'}],
                  })(<Input placeholder="请输入大库名称" maxLength={50} />)}
                </FormItem>
              </Col>

              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="公司名称">
                  {getFieldDecorator('unitName', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    comList.length ? (
                      <HOCSelect
                        placeholder="请输入公司名称"
                        onChange={this.comInfoChange}
                        disabled={comDis || statusFlag}
                      >
                        {comOption}
                      </HOCSelect>
                    ) : (
                      <Input placeholder="请输入公司名称" disabled={comDis || statusFlag} />
                    )
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="统一社会信用代码">
                  {getFieldDecorator('uniCreditCode', {
                    rules: [{ required: true, message: '请选择' }],
                  })(<Input placeholder="请输入" disabled />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="开户地区">
                  {getFieldDecorator('areaId', {
                    rules: [{ required: true, message: '请输入' }],
                  })(
                    <Area
                      labelInValue
                      onChange={value => this.getData(value, 'areaId')}
                      disabled={bDisable}
                    />
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="所属公积金机构">
                  {getFieldDecorator('blngAccoOrg', {
                    rules: [{ required: true, message: '请输入所属公积金机构' }],
                  })(<Input placeholder="请输入所属公积金机构" maxLength={50} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="是否可突破上限">
                  {getFieldDecorator('isExceedCeiling', {
                    rules: [{ required: false, message: '请输入' }],
                  })(
                    <HOCSelect placeholder="请选择" disabled={statusFlag}>
                      {dictOL(YES_NO_FLAG)}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem
                  label={
                    <span>
                      公积金组<span style={{ color: '#999999' }}>(可多选)</span>
                    </span>
                  }
                >
                  {getFieldDecorator('accuLsPkgIdsList', {
                    rules: [{ required: true, message: '请选择' }],
                  })(
                    <HOCSelect
                      onChange={this.paywayChange}
                      placeholder="请选择本大库支持的政策名称"
                      mode="multiple"
                      disabled={statusFlag}
                    >
                      {supplyList.map(value => (
                        <Option
                          key={value.accuLsPkgId}
                          value={value.accuLsPkgId}
                          onChange={this.test}
                        >
                          {value.accuLsPkgName}
                        </Option>
                      ))}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="开户行">
                  {getFieldDecorator('custBankName', {
                    rules: [{ required: false, message: '请输入' }],
                  })(<Input placeholder="请输入" maxLength={50} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="银行账号">
                  {getFieldDecorator('custBankId', {
                    rules: [
                      { required: false, message: '最大长度不超过25位数字', pattern: /^\d{1,25}$/ },
                    ],
                  })(<Input placeholder="请输入银行账户信息" maxLength={25} />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              {Number(sysCode) !== 2 && (
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label={this.renderRepListTip()}>
                    {getFieldDecorator('respList', {
                      rules: [{ required: true, message: '请选择申报负责人' }],
                    })(
                      <HOCSelect mode="multiple" style={{ width: '100%' }} placeholder="请选择">
                        {waresave.respDataList.map(value => (
                          <Option key={value.userId} value={value.userId}>
                            {value.userName}
                          </Option>
                        ))}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              )}
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="备注">
                  {getFieldDecorator('remark', {})(
                    <TextArea placeholder="请输入备注" maxLength={100} />
                  )}
                </FormItem>
              </Col>
            </Row>
          </Card>
          <FooterToolbar>
            <Button onClick={this.cancel} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button type="primary" onClick={this.submitAll} loading={submitting}>
              提交
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default AccuWareEdit;
